//
//  FXOnceEvent.swift
//  FXEvent
//
//  Created by Fanxx on 2021/11/23.
//

import Foundation
import BasicExtensions

///只触发一次的事件，触发后马上移除触发过的handler
open class FXOnceEvent<EventType: FXEventType>: FXEvent<EventType.ParameterType>, FXEventProxyType {
    private let eventIdentifier = "__fxOnceEvent"
    public var event: EventType {
        didSet {
            oldValue.removeBlock(self.eventIdentifier)
            self.event.addBlock(self.eventIdentifier) { [weak self] p in self?.sendActions(for: p) }
        }
    }
    public override var isEnabled: Bool {
        get { return self.event.isEnabled }
        set {
            self.event.isEnabled = newValue
            if let p = self.lastParameter, newValue {
                self.sendActions(for: p)
            }
        }
    }
    public init(_ event: EventType) {
        self.event = event
        super.init()
        self.event.addBlock(self.eventIdentifier) { [weak self] p in self?.sendActions(for: p) }
    }
    deinit {
        self.event.removeBlock(self.eventIdentifier)
    }
    ///若已触发事件参数，则不为nil，若未触发则为nil，当不为nil时每次新添加事件处理都马上触发并移除，每次调用fire方法后(若被中断则丢弃后续处理)该值不为nil，若不想后续即时触发需调用reset()
    open var lastParameter: ParameterType?
    
    open override func addTarget(_ target: AnyObject, action: Selector) {
        if self.isEnabled, let lastParameter = lastParameter {
            _ = target.perform(action, with: lastParameter)
//            doAction(for: target, selector: action, arg: lastParameter)
        }else{
            super.addTarget(target, action: action)
        }
    }
    /// 添加事件处理
    open override func addBlock(_ identifier: String, block: @escaping (ParameterType) -> Void) {
        if self.isEnabled, let lastParameter = lastParameter {
            block(lastParameter)
        }else{
            super.addBlock(identifier, block: block)
        }
    }
    /// 添加事件处理
    open override func addBlock(_ block: @escaping (ParameterType) -> Void) {
        if self.isEnabled, let lastParameter = lastParameter {
            block(lastParameter)
        }else{
            super.addBlock(block)
        }
    }
    /// 触发事件
    open override func sendActions(for parameter: ParameterType) {
        self.lastParameter = parameter
        if self.isEnabled {
            super.sendActions(for: parameter)
            self.removeAllActions()
        }
    }
    ///重置为未触发状态
    open func reset() {
        self.lastParameter = nil
    }
}
extension FXEventType {
    /// 转为只处理一次的事件
    public func asOnce() -> FXOnceEvent<Self> {
        return FXOnceEvent(self)
    }
}

